package com.mianyang.zhangsan.common.util;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * 操作员解析工具
 * @author jiangjr
 * @date 2022-11-14
 */
public class OperationManHelper {

    public static String getAccountName() {
        // 获取requestAttribute
        String man = "admin";
        HttpServletRequest request = getRequest();
        if (request != null) {
            Object accountName = request.getAttribute("accountName");
            if (accountName != null) {
                return accountName.toString();
            }
        }
        return man;
    }

    public static Long getAccountId() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            Object accountId = request.getAttribute("accountId");
            if (accountId != null) {
                return Long.parseLong(accountId.toString());
            }
        }
        return null;
    }

    private static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            // 获取HttpServletRequest
            return (HttpServletRequest)requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        }
        return null;
    }

}
